package com.compass.doctor.ui.patient


import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.activity.viewModels
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityVideoAnswerBinding
import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.patient.viewmodel.VideoCallViewModel
import com.compass.doctor.ui.prescription.PrescriptionTypeActivity
import com.compass.doctor.utils.SelectPicturesUtil
import com.compass.framework.constant.CANCEL_INVITE
import com.compass.framework.constant.CLOSE_EVENT
import com.compass.framework.constant.NIM_APP_KEY
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.invisible
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.glide.setUrlRound
import com.compass.framework.helper.CompassAppHelper
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.ChannelExt
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.StatusBarSettingHelper
import com.compass.framework.utils.getStringFromResource
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.netease.lava.nertc.sdk.LastmileProbeResult
import com.netease.lava.nertc.sdk.NERtc
import com.netease.lava.nertc.sdk.NERtcCallback
import com.netease.lava.nertc.sdk.NERtcCallbackEx
import com.netease.lava.nertc.sdk.NERtcConstants
import com.netease.lava.nertc.sdk.NERtcEx
import com.netease.lava.nertc.sdk.NERtcUserJoinExtraInfo
import com.netease.lava.nertc.sdk.NERtcUserLeaveExtraInfo
import com.netease.lava.nertc.sdk.stats.NERtcAudioVolumeInfo
import com.netease.lava.nertc.sdk.video.NERtcEncodeConfig
import com.netease.lava.nertc.sdk.video.NERtcRemoteVideoStreamType
import com.netease.lava.nertc.sdk.video.NERtcVideoConfig
import com.netease.lava.nertc.sdk.video.NERtcVideoStreamType
import com.netease.nimlib.sdk.avsignalling.event.InvitedEvent
import com.netease.nimlib.sdk.avsignalling.model.ChannelBaseInfo
import com.netease.yunxin.kit.alog.ALog
import com.netease.yunxin.kit.call.p2p.model.NECallType
import com.netease.yunxin.kit.corekit.im.model.UserInfo
import com.netease.yunxin.nertc.nertcvideocall.model.impl.state.CallState
import com.netease.yunxin.nertc.ui.base.Constants
import com.netease.yunxin.nertc.ui.floating.FloatingPermission
import com.netease.yunxin.nertc.ui.p2p.CallUIFloatingWindowMgr
import com.netease.yunxin.nertc.ui.p2p.CallUIOperationsMgr
import com.netease.yunxin.nertc.ui.utils.AppForegroundWatcherHelper
import com.netease.yunxin.nertc.ui.utils.PermissionTipDialog
import com.netease.yunxin.nertc.ui.view.OverLayPermissionDialog
import java.nio.ByteBuffer


/**
 * Description： 视频被叫
 * Date:2024/6/13 14:21
 */
class VideoAnswerActivity : BaseVBActivity<ActivityVideoAnswerBinding>() {


    private lateinit var inviteEvent: InvitedEvent
    private val videoCallViewModel: VideoCallViewModel by viewModels()
    private lateinit var userInfo: UserInfo//云信信息
    private lateinit var patientId: String//患者ID
    private var neRtcCallback: NERtcCallback = object : NERtcCallbackEx {
        override fun onUserSubStreamVideoStart(uid: Long, maxProfile: Int) {}
        override fun onUserSubStreamVideoStop(uid: Long) {}
        override fun onUserAudioMute(uid: Long, muted: Boolean) {}
        override fun onUserVideoMute(uid: Long, muted: Boolean) {}
        override fun onUserVideoMute(
            streamType: NERtcVideoStreamType,
            uid: Long,
            muted: Boolean
        ) {
        }

        override fun onFirstAudioDataReceived(uid: Long) {}

        override fun onFirstVideoDataReceived(uid: Long) {}
        override fun onFirstVideoDataReceived(streamType: NERtcVideoStreamType, uid: Long) {}
        override fun onFirstAudioFrameDecoded(userID: Long) {}
        override fun onFirstVideoFrameDecoded(userID: Long, width: Int, height: Int) {}
        override fun onFirstVideoFrameDecoded(
            streamType: NERtcVideoStreamType,
            userID: Long,
            width: Int,
            height: Int
        ) {
        }

        override fun onUserVideoProfileUpdate(uid: Long, maxProfile: Int) {}
        override fun onAudioDeviceChanged(selected: Int) {}
        override fun onAudioDeviceStateChange(deviceType: Int, deviceState: Int) {}
        override fun onVideoDeviceStageChange(deviceState: Int) {}
        override fun onConnectionTypeChanged(newConnectionType: Int) {}
        override fun onReconnectingStart() {}
        override fun onReJoinChannel(result: Int, channelId: Long) {}
        override fun onAudioMixingStateChanged(reason: Int) {}
        override fun onAudioMixingTimestampUpdate(timestampMs: Long) {}
        override fun onAudioEffectTimestampUpdate(id: Long, timestampMs: Long) {}
        override fun onAudioEffectFinished(effectId: Int) {}
        override fun onLocalAudioVolumeIndication(volume: Int) {}
        override fun onLocalAudioVolumeIndication(volume: Int, vadFlag: Boolean) {}
        override fun onRemoteAudioVolumeIndication(
            volumeArray: Array<NERtcAudioVolumeInfo>,
            totalVolume: Int
        ) {
        }

        override fun onLiveStreamState(taskId: String, pushUrl: String, liveState: Int) {}
        override fun onConnectionStateChanged(state: Int, reason: Int) {}
        override fun onCameraFocusChanged(rect: Rect) {}
        override fun onCameraExposureChanged(rect: Rect) {}
        override fun onRecvSEIMsg(userID: Long, seiMsg: String) {}
        override fun onAudioRecording(code: Int, filePath: String) {}
        override fun onError(code: Int) {}
        override fun onWarning(code: Int) {}
        override fun onApiCallExecuted(apiName: String, result: Int, message: String) {}
        override fun onMediaRelayStatesChange(state: Int, channelName: String) {}
        override fun onMediaRelayReceiveEvent(event: Int, code: Int, channelName: String) {}
        override fun onLocalPublishFallbackToAudioOnly(
            isFallback: Boolean,
            streamType: NERtcVideoStreamType
        ) {
        }

        override fun onRemoteSubscribeFallbackToAudioOnly(
            uid: Long,
            isFallback: Boolean,
            streamType: NERtcVideoStreamType
        ) {
        }

        override fun onLastmileQuality(quality: Int) {}
        override fun onLastmileProbeResult(result: LastmileProbeResult) {}
        override fun onMediaRightChange(
            isAudioBannedByServer: Boolean,
            isVideoBannedByServer: Boolean
        ) {
        }

        override fun onRemoteVideoSizeChanged(
            userId: Long,
            videoType: NERtcVideoStreamType,
            width: Int,
            height: Int
        ) {
        }

        override fun onLocalVideoRenderSizeChanged(
            videoType: NERtcVideoStreamType,
            width: Int,
            height: Int
        ) {
        }

        override fun onVirtualBackgroundSourceEnabled(enabled: Boolean, reason: Int) {}
        override fun onUserSubStreamAudioStart(uid: Long) {}
        override fun onUserSubStreamAudioStop(uid: Long) {}
        override fun onUserSubStreamAudioMute(uid: Long, muted: Boolean) {}
        override fun onPermissionKeyWillExpire() {}
        override fun onUpdatePermissionKey(key: String, error: Int, timeout: Int) {}
        override fun onLocalVideoWatermarkState(
            videoStreamType: NERtcVideoStreamType,
            state: Int
        ) {
        }

        override fun onUserDataStart(uid: Long) {}
        override fun onUserDataStop(uid: Long) {}
        override fun onUserDataReceiveMessage(
            uid: Long,
            bufferData: ByteBuffer,
            bufferSize: Long
        ) {
        }

        override fun onUserDataStateChanged(uid: Long) {}
        override fun onUserDataBufferedAmountChanged(uid: Long, previousAmount: Long) {}
        override fun onLabFeatureCallback(key: String, param: Any) {}

        //本端用户加入房间结果回调
        override fun onJoinChannel(result: Int, channelId: Long, elapsed: Long, uid: Long) {
            if (result == NERtcConstants.ErrorCode.OK) {
                // 加入房间成功
                mBinding.videoViewSmall.visible()
                NERtcEx.getInstance().setupLocalVideoCanvas(mBinding.videoViewSmall)
                //加入房间前提前设置好视频开启状态
                NERtcEx.getInstance()
                    .enableLocalVideo(NERtcVideoStreamType.kNERtcVideoStreamTypeMain, true)
                innerStop()
                mBinding.ivPrescription.visible()
                mBinding.ivSwitchCamera.visible()
                mBinding.llOnTheCallOperation.visible()
                mBinding.llOnTheCallingOperation.gone()

                LogUtil.d("加入房间成功", tag = tag)
            } else {
                // 加入房间失败 ，退出页面
                finish()
            }
        }

        override fun onLeaveChannel(result: Int) {

        }

        override fun onUserJoined(uid: Long) {
            //设置远端画布
            NERtcEx.getInstance().setupRemoteVideoCanvas(mBinding.videoViewBig, uid)
            LogUtil.d("用户加入房间", tag = tag)
        }

        override fun onUserJoined(uid: Long, joinExtraInfo: NERtcUserJoinExtraInfo) {
        }

        override fun onUserLeave(uid: Long, reason: Int) {

            LogUtil.d("用户离开房间回调", tag = tag)
        }

        override fun onUserLeave(
            uid: Long,
            reason: Int,
            leaveExtraInfo: NERtcUserLeaveExtraInfo
        ) {
        }

        override fun onUserAudioStart(uid: Long) {
            LogUtil.d(
                "  当房间中的其他用户发布视频流时，本端会触发 onUserVideoStart 回调。",
                tag = tag
            )

        }

        override fun onUserAudioStop(uid: Long) {}
        override fun onUserVideoStart(uid: Long, maxProfile: Int) {
//            NERtcEx.getInstance().setupLocalVideoCanvas(mBinding.videoViewSmall)
            //对方开启视频，按需设置画布及订阅视频
            NERtcEx.getInstance().setupRemoteVideoCanvas(mBinding.videoViewBig, uid)
            NERtcEx.getInstance().subscribeRemoteVideoStream(
                uid,
                NERtcRemoteVideoStreamType.kNERtcRemoteVideoStreamTypeHigh,
                true
            )
        }

        override fun onUserVideoStop(uid: Long) {
            //释放之前绑定的画布
            NERtcEx.getInstance().setupRemoteVideoCanvas(null, uid)
        }

        override fun onDisconnect(reason: Int) {
            // 与服务器断连 ，退出页面
            finish()
        }

        override fun onClientRoleChange(oldRole: Int, newRole: Int) {} //*******其他一些回调******
    }

    protected val isFromFloatingWindow: Boolean
        get() {
            return intent.getBooleanExtra(
                Constants.PARAM_KEY_FLAG_IS_FROM_FLOATING_WINDOW,
                false
            ) || CallUIFloatingWindowMgr.isFloating()
        }



    private var overLayPermissionDialog: OverLayPermissionDialog? = null

    private val watcher = object : AppForegroundWatcherHelper.Watcher() {
        override fun onBackground() {
//            if (uiConfig?.enableFloatingWindow == true &&
//                uiConfig?.enableAutoFloatingWindowWhenHome == true &&
//                CallUIOperationsMgr.currentCallState() != CallState.STATE_INVITED &&
//                CallUIOperationsMgr.currentCallState() != CallState.STATE_IDLE
//            ) {
//                doShowFloatingWindowInner()
//            }

        }
    }

    /**
     * 禁止锁屏
     */
    private fun configWindow() {
        window.addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        )
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
    }

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarSettingHelper.setStatusBarTranslucent(this)
        StatusBarSettingHelper.statusBarLightMode(this@VideoAnswerActivity, true)
//        configWindow()
        inviteEvent = intent.serializable("invitedEvent")!!
        havePermission()
        if (inviteEvent.channelBaseInfo.channelExt.isNotEmpty()){
            val type = object : TypeToken<ChannelExt>() {}.type
            try {
                val ext: ChannelExt = Gson().fromJson(inviteEvent.channelBaseInfo.channelExt, type)
                LogUtil.d("消息通知 type===${ext.toJson()}")
                mBinding.ivPatientAvatar.setUrlCircle(ext.avatar)
                mBinding.tvPatientName.text = ext.name
                ext.id?.let {
                    patientId = it
                }
                ext.name?.let {
                    userInfo = UserInfo(inviteEvent.fromAccountId, it, ext.avatar)
                }


            } catch (e: JsonSyntaxException) {
                e.printStackTrace()
            }
        }
        videoCallViewModel.updateOnlineStatus("1")
        // 配置前后台监听
        AppForegroundWatcherHelper.addWatcher(watcher)
    }


    override fun initData() {
        // 初始化SDK
        try {
            NERtc.getInstance()
                .init(CompassAppHelper.getApplication(), NIM_APP_KEY, neRtcCallback, null)
        } catch (e: Exception) {
            e.printStackTrace()
            showToast("NERtc初始化失败")
            finish()
            return
        }
        //指定前置摄像头
        NERtcEx.getInstance()
            .switchCameraWithPosition(NERtcConstants.CameraPosition.CAMERA_POSITION_FRONT)
        //指定后置摄像头
//        NERtcEx.getInstance().switchCameraWithPosition(NERtcConstants.CameraPosition.CAMERA_POSITION_BACK)

        //设置视频  通用 1 对 1 聊天场景
        NERtcEx.getInstance().setChannelProfile(NERtcConstants.RTCChannelProfile.LIVE_BROADCASTING)
        //设置音频profile为标准模式，scenario为语音场景
        NERtcEx.getInstance().setAudioProfile(
            NERtcConstants.AudioProfile.STANDARD,
            NERtcConstants.AudioScenario.SPEECH
        );
        //设置本地视频参数
        val videoConfig = NERtcVideoConfig()
        videoConfig.width = 720
        videoConfig.height = 1080
        videoConfig.frameRate = NERtcEncodeConfig.NERtcVideoFrameRate.FRAME_RATE_FPS_24
        NERtcEx.getInstance().setLocalVideoConfig(videoConfig)
        // 禁用双流模式
        NERtcEx.getInstance().enableDualStreamMode(false)
        //设置本地画布


        innerPlay(this)
        LiveDataBus.get().with(CLOSE_EVENT, ChannelBaseInfo::class.java).observe(this) {
            //离开频道
            videoCallViewModel.leave(it)
            leaveAndClose()
        }

        LiveDataBus.get().with(CANCEL_INVITE, ChannelBaseInfo::class.java).observe(this) {
            //离开频道
            leaveAndClose()
        }


        videoCallViewModel.joinChannelLiveData.observe(this) {
            it?.let {
                //小画布置于大画布上面
                mBinding.videoViewSmall.setZOrderMediaOverlay(true)
                NERtcEx.getInstance().setupLocalVideoCanvas(mBinding.videoViewSmall)
                NERtcEx.getInstance()
                    .startVideoPreview(NERtcVideoStreamType.kNERtcVideoStreamTypeMain)
                //加入房间
                LogUtil.d("${it.toJson()}", tag = tag)
                var channelName = it.channelBaseInfo.channelName
                UserInfoManager.getImUserAccount()?.let { uid ->
                    //token暂时传空  等后台做好了再传
                    //加入房间
                    NERtcEx.getInstance()
                        .startVideoPreview()//加入房间时，调用 stopVideoPreview(streamType) 方法停止预览
                    NERtcEx.getInstance().joinChannel(null, channelName, uid.toLong(), null)
                }

            }
        }


    }


    private fun doShowFloatingWindowInner() {
        ALog.d(tag, "doShowFloatingWindowInner")
        if (!FloatingPermission.isFloatPermissionValid(this)) {
            if (overLayPermissionDialog?.isShowing != true) {
                showOverlayPermissionDialog {
                    FloatingPermission.requireFloatPermission(this)
                }
            }
            return
        }
        if (!CallUIFloatingWindowMgr.isFloating()) {
            CallUIFloatingWindowMgr.showFloat(this.applicationContext)
        }
        finish()
    }

    protected open fun showOverlayPermissionDialog(clickListener: View.OnClickListener): OverLayPermissionDialog {
        return OverLayPermissionDialog(this, clickListener).apply {
            this@VideoAnswerActivity.overLayPermissionDialog = this
            show()
        }
    }
    override fun onResume() {
        super.onResume()
//        if (overLayPermissionDialog?.isShowing == true &&
//            FloatingPermission.isFloatPermissionValid(this)
//        ) {
//            overLayPermissionDialog?.dismiss()
//            overLayPermissionDialog = null
//        }
//        if (CallUIFloatingWindowMgr.isFloating()) {
//            CallUIFloatingWindowMgr.releaseFloat(false)
//        }
//        when (cameraDeviceStatus) {
//            NERtcConstants.VideoDeviceState.DISCONNECTED,
//            NERtcConstants.VideoDeviceState.FREEZED,
//            NERtcConstants.VideoDeviceState.UNKNOWNERROR -> {
//                callEngine.enableLocalVideo(false)
//                if (callParam.callType != NECallType.VIDEO) {
//                    return
//                }
//                if (isLocalMuteVideo && uiConfig?.closeVideoType != Constants.CLOSE_TYPE_MUTE) {
//                    return
//                }
//                callEngine.enableLocalVideo(true)
//            }
//        }
    }



    /**
     * 判断是否有权限
     */
    private fun havePermission() {
        //判断是否有权限
        if (XXPermissions.isGranted(
                this,
                Permission.RECORD_AUDIO,
                Permission.CAMERA
            )
        ) {
            requestPermission()
        } else {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(R.string.permission_explain))
                .setMessage(getStringFromResource(R.string.video_permission_logs))
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermission()
                    it?.dismiss()
                }.create().show()
        }
    }


    /**
     * 请求权限
     */
    private fun requestPermission() {
        XXPermissions.with(this)
            //小米应用市场不允许提前获取相册拍照权限，这里先获取存储权限，进入到相册选择页面点击拍照按钮时在获取拍照权限
            .permission(Permission.RECORD_AUDIO)
            .permission(Permission.CAMERA)
            .unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips(R.string.default_agree_permission)
                        return
                    }
//                    NERtcEx.getInstance() .startVideoPreview()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    TipsToast.showTips(R.string.default_agree_permission)
                }
            })
    }

    var tag = "VideoCall:==="
    private var isMuteAudio = false
    private var isMuteVideo = false
    private var uid: Long = -100000
    override fun intListener() {
        //接听
        mBinding.btnAnswerVideo.onClick {

            //自己在频道中对应的uid，大于零有效，无效时服务器会分配随机唯一的uid， 也可以自己生成，但要保证唯一性 这里先写死 加入房间的时候也要用到
            UserInfoManager.getImUserAccount()?.let {
                uid = it.toLong()
            }

            mBinding.videoViewBig.visible()
            videoCallViewModel.acceptInvite(inviteEvent, uid)
            videoCallViewModel.remoteUserJoinChannelLiveData.observe(this) {
                it?.let {

                    NERtcEx.getInstance()
                        .startVideoPreview()//加入房间时，调用 stopVideoPreview(streamType) 方法停止预览
                    NERtcEx.getInstance()
                        .joinChannel(null, it.channelBaseInfo.channelName, uid, null)

                    //接通成功以后
//                    mBinding.llSimpleInfo.gone()

                }
            }
        }

        //关闭打开音频
        mBinding.ivMuteAudio.onClick {
            isMuteAudio = !isMuteAudio
            mBinding.ivMuteAudio.setImageResource(
                if (isMuteAudio) com.netease.yunxin.nertc.ui.R.drawable.voice_off else com.netease.yunxin.nertc.ui.R.drawable.voice_on
            )
            NERtcEx.getInstance().muteLocalAudioStream(isMuteAudio)

        }
        //切换摄像头
        mBinding.ivSwitchCamera.onClick {
            NERtcEx.getInstance().switchCamera()
            if (::userInfo.isInitialized&&::patientId.isInitialized){
                PatientChatActivity.start(
                    this, userInfo,
                    patientId
                )
            }else{
                showToast("患者信息异常")
            }
//            WebDetailActivity.start(
//                this, "https://www.baidu.com/",
//                "测试"
//            )
        }

        //关闭打开视频
        mBinding.ivMuteVideo.onClick {
            isMuteVideo = !isMuteVideo
            mBinding.ivMuteVideo.setImageResource(if (isMuteVideo) com.netease.yunxin.nertc.ui.R.drawable.cam_off else com.netease.yunxin.nertc.ui.R.drawable.cam_on)
            NERtcEx.getInstance().muteLocalVideoStream(isMuteVideo)


        }


        mBinding.btnHangUp.onClick {
            //挂断--拒绝邀请
            videoCallViewModel.rejectInvite(inviteEvent)
            leaveAndClose()
        }


        //通话结束---离开频道
        mBinding.ivHangUp.onClick {
            //离开频道
            videoCallViewModel.leave(inviteEvent.channelBaseInfo)
            leaveAndClose()
        }

        //开处方
        mBinding.ivPrescription.onClick {

            if (::userInfo.isInitialized&&::patientId.isInitialized){
                PrescriptionTypeActivity.start(
                    this, userInfo,
                    patientId,
                    ""
                )
            }else{
                showToast("患者信息异常，暂时无法开具")
            }


        }
    }


    /**
     * 离开并关闭
     */
    private fun leaveAndClose() {
        innerStop()
        videoCallViewModel.updateOnlineStatus("0")
        //结束通话
        NERtcEx.getInstance().leaveChannel()
        //释放SDK
        NERtcEx.getInstance().release()
        finish()
    }

    private var player: MediaPlayer = MediaPlayer()
    private fun innerPlay(context: Context) {
        player.run {
            if (isPlaying) {
                stop()
            }
            reset()
            release()
        }
        player = MediaPlayer().apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                setAudioAttributes(
                    AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_MUSIC)
                        .build()
                )
            }
            val afd =
                context.resources.openRawResourceFd(com.netease.yunxin.nertc.ui.R.raw.avchat_ring)
            if (afd == null) {
                LogUtil.e("can't open resources by ringId")
                return@apply
            }
            try {
                setDataSource(
                    afd.fileDescriptor,
                    afd.startOffset,
                    afd.length
                )
                isLooping = true
                prepare()
                start()
            } catch (e: Exception) {

            }
        }
    }

    private fun innerStop() {
        player.run {
            if (isPlaying) {
                stop()
            }
        }
    }


    override fun onBackPressed() {

        CommonMessageDialog.Builder(this)
            .setTitle("温馨提示")
            .setMessage("是否要结束当前通话?")
            .setConfirm(getStringFromResource(R.string.default_confirm))

            .setCancel(getString(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                //离开频道
                videoCallViewModel.leave(inviteEvent.channelBaseInfo)
                leaveAndClose()
                it?.dismiss()
                super.onBackPressed()
            }.create().show()

    }

    override fun onDestroy() {
        super.onDestroy()
        videoCallViewModel.updateOnlineStatus("0")
        innerStop()
        //结束通话
        NERtcEx.getInstance().leaveChannel()
        //释放SDK
        NERtcEx.getInstance().release()
    }

}